package com.wave.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wave.common.core.domain.BaseEntity;
import com.wave.common.core.domain.PageQuery;
import com.wave.common.core.page.TableDataInfo;
import com.wave.common.utils.StringUtils;
import com.wave.system.domain.SysAlarmRecord;
import com.wave.system.domain.SysNgRecord;
import com.wave.system.domain.bo.SysNgRecordBo;
import com.wave.system.domain.vo.SysNgRecordVo;
import com.wave.system.mapper.SysAlarmRecordMapper;
import com.wave.system.mapper.SysNgRecordMapper;
import com.wave.system.service.ISysNgRecordService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * NG记录Service业务层处理
 *
 * @author wave
 * @date 2024-10-12
 */
@RequiredArgsConstructor
@Service
public class SysNgRecordServiceImpl implements ISysNgRecordService {

    private static final Logger log = LoggerFactory.getLogger(SysNgRecordServiceImpl.class);
    private final SysNgRecordMapper baseMapper;
    private final SysAlarmRecordMapper alarmRecordMapper;

    /**
     * 查询NG记录
     */
    @Override
    public SysNgRecordVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询NG记录列表
     */
    @Override
    public TableDataInfo<SysNgRecordVo> queryPageList(SysNgRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysNgRecord> lqw = buildQueryWrapper(bo);
        Page<SysNgRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询NG记录列表
     */
    @Override
    public List<SysNgRecordVo> queryList(SysNgRecordBo bo) {
        LambdaQueryWrapper<SysNgRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysNgRecord> buildQueryWrapper(SysNgRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysNgRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTaskType() != null, SysNgRecord::getTaskType, bo.getTaskType());
        lqw.eq(StringUtils.isNotBlank(bo.getSn()), SysNgRecord::getSn, bo.getSn());
        lqw.eq(StringUtils.isNotBlank(bo.getNgReason()), SysNgRecord::getNgReason, bo.getNgReason());
        lqw.orderByDesc(SysNgRecord::getCreateTime);
        return lqw;
    }

    /**
     * 新增NG记录
     */
    @Override
    public Boolean insertByBo(SysNgRecordBo bo) {
        SysNgRecord add = BeanUtil.toBean(bo, SysNgRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改NG记录
     */
    @Override
    public Boolean updateByBo(SysNgRecordBo bo) {
        SysNgRecord update = BeanUtil.toBean(bo, SysNgRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysNgRecord entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除NG记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    @Transactional
    public void saveNgAndAlarmRecord(String snCode, String reason) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime fiveMinutesAgo = now.minusMinutes(5L);
        LambdaQueryWrapper<SysNgRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysNgRecord::getSn, snCode)
            .eq(SysNgRecord::getNgReason, reason)
            .ge(BaseEntity::getCreateTime, fiveMinutesAgo)
            .orderByDesc(BaseEntity::getCreateTime).last("limit 1");
        SysNgRecord sysNgRecord = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(sysNgRecord)) {
            log.warn("物料码:{}5分钟内已记录过NG和报警记录，暂不处理", snCode);
            return;
        }
        SysNgRecord ngRecord = new SysNgRecord();
        ngRecord.setTaskType(0);
        ngRecord.setSn(snCode);
        ngRecord.setNgReason(reason);
        baseMapper.insert(ngRecord);

        SysAlarmRecord alarmRecord = new SysAlarmRecord();
        alarmRecord.setAlarmTime(new Date());
        alarmRecord.setAlarmType(1);
        alarmRecord.setAlarmContent(reason);
        alarmRecordMapper.insert(alarmRecord);
    }
}
